package assets
{
	import events.LoadedEvent;
	
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	
	/**
	 * 位图类资源管理器
	 */	
	public class AssetBitmapData extends EventDispatcher
	{
		///////////////////////////////////////////////
		private var loadingList:Array = new Array;
		private var currentLoadingURL:String;
		private var lc:LoaderContext = new LoaderContext(true);
		private var loader:Loader;
		
		///////////////////////////////////////////////
		public function AssetBitmapData()
		{
			loader = new Loader;
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onError);
		}
		
		private function onError(e:IOErrorEvent):void
		{
			var errorInfo:String ="没有此资源："+ currentLoadingURL;
			throw new Error(errorInfo);
		}
		
		public function load(URL:String):void
		{
			if(loadingList.indexOf(URL) > -1)return;
			
			if(Asset.resBitmapDatas[URL] == undefined)
			{
				loadingList.push(URL);
				
				if(loadingList.length==1)loadNext();
				
			}else{
				dispatchEvent(new LoadedEvent(URL,LoadedEvent.BITMAPDATA_COMPLETE));
			}
		}
		
		///////////////////////////////////////////////
		private function loadNext():void
		{
			currentLoadingURL = loadingList[0];
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onloadComplete);
			loader.load(new URLRequest(currentLoadingURL),lc);
		}
		
		private function onloadComplete(e:Event):void
		{
			var ld:LoaderInfo = e.currentTarget as LoaderInfo;
			Asset.resBitmapDatas[currentLoadingURL] = ((ld.loader.content) as Bitmap).bitmapData.clone();
			loadingList.splice(0,1);
			ld.loader.unload();
			dispatchEvent(new LoadedEvent(currentLoadingURL,LoadedEvent.BITMAPDATA_COMPLETE));
			
			if(loadingList.length == 0)
			{
				ld.loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onloadComplete);
				return;
			}
			
			loadNext();
		}
	}
}